#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    vector<double> res;
    bool flag;
    void dfs(string cur, string target, double path, unordered_map<string, vector<pair<string, double>> >& g, unordered_map<string, int>& visit) {
        if (flag == false)return;
        if (cur == target) {
            flag = false;
            res.push_back(path);
            return;
        }

        for (int i = 0; i < g[cur].size(); i++) {
            if (visit[g[cur][i].first] == 0) {
                visit[g[cur][i].first] = 1;
                dfs(g[cur][i].first, target, path * g[cur][i].second, g, visit);
                visit[g[cur][i].first] = 0;
            }
        }
    }
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
        unordered_map<string, vector<pair<string, double>> > g;
        unordered_map<string, int> visit;
        res.clear();
        flag = true;
        int n = equations.size();
        for (int i = 0; i < n; i++) {
            g[equations[i][0]].push_back({ equations[i][1],values[i] });
            g[equations[i][1]].push_back({ equations[i][0],1.0 / values[i] });
        }
        int m = queries.size();
        for (int i = 0; i < m; i++) {
            if (g.find(queries[i][0]) == g.end()) {
                res.push_back(-1.0);
                continue;
            }

            flag = true;
            visit[queries[i][0]] = 1;
            dfs(queries[i][0], queries[i][1], 1, g, visit);
            visit[queries[i][0]] = 0;

            if (flag)res.push_back(-1.0);

        }
        return res;
    }
};